# coding:utf-8
#!/usr/bin/env python

'''
用来检测同一网段的IP，mac地址
'''

__author__ = 'SAF'

import threading
import os
from time import sleep
import time

from ip2mac import IP2MAC


def ping(ip, usedIP):
    x = os.popen("ping %s -n 1" % str(ip))
    res = x.readlines()
    if check_res(res):
        for each in res:
            # print ip, res[3].decode('gbk'),
            usedIP.append(ip)
            return
    else:
        #print ip, "can't reach"
        pass


def check_res(res):
    for each in res:
        if "TTL" in each:
            return True
        else:
            continue

def is_off_line(use_able_ip_nums, threshold):
    if use_able_ip_nums < threshold:
        return True
    else:
        return False


if __name__ == "__main__":
    ips = []
    for i in xrange(1, 255):
        ips.append("119.78.239.%d" % i)
    ip_nums_file = open(r'ip_nums_file', 'a')
    last_time = 100
    while last_time:
        #print ips
        used_ip = []
        for each in ips:
            t = threading.Timer(0, ping, args=[each, used_ip])
            t.start()
        #ping("192.168.14.1")
        sleep(20)
        txt = "at " + time.ctime() + ' total used ip is ' + str(len(used_ip)) + '\n'

        print txt,
        if is_off_line(len(used_ip),10):
            print "the net work is down...."
            ip_nums_file.write(txt+"the network may be down!")
        last_time = last_time - 1

    ip_nums_file.close()

        # while (1):
        # g = IP2MAC()
        # for each in used_ip:
        #     print each, g.getMac(each)

        # # used_ip.sort()
        # for each in used_ip:
        #     print each